// controllers/userController.js
const pool = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { sendResponse } = require('../utils/response');

// 用户注册
const registerUser = async (req, res) => {
  const { username, password,role='user' } = req.body;
  if (!username || !password) {
    return sendResponse(res, 400, '用户名和密码必填');
  }
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查用户是否已存在
    const [existing] = await connection.execute('SELECT * FROM users WHERE username = ?', [username]);
    if (existing.length > 0) {
      await connection.rollback();
      return sendResponse(res, 409, '用户名已存在');
    }
    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);
    // 插入用户
    const [result] = await connection.execute(
      'INSERT INTO users (username, password, role, is_active) VALUES (?, ?, ?, ?)',
      [username, hashedPassword, role, 1]
    );
    await connection.commit();
    sendResponse(res, 201, '用户注册成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '用户注册失败', error.message);
  } finally {
    connection.release();
  }
};

// 用户登录
const loginUser = async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    return sendResponse(res, 400, '用户名和密码必填');
  }
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 获取用户
    const [users] = await connection.execute(
      'SELECT * FROM users WHERE username = ? AND is_active = 1',
      [username]
    );
    if (users.length === 0) {
      await connection.rollback();
      return sendResponse(res, 401, '用户名或密码错误');
    }
    const user = users[0];
    // 验证密码
    const validPassword = await bcrypt.compare(password, user.password);
    if (!validPassword) {
      await connection.rollback();
      return sendResponse(res, 401, '用户名或密码错误');
    }
    // 生成 JWT
    const token = jwt.sign(
      { id: user.id, username: user.username, role: user.role },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );
    await connection.commit();
    sendResponse(res, 200, '登录成功', { token, id: user.id});

  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '登录失败', error.message);
  } finally {
    connection.release();
  }
};

// 获取当前用户信息
const getCurrentUser = async (req, res) => {
  // req.user 是通过 authenticateToken 中间件添加的
  sendResponse(res, 200, '获取用户信息成功', { user: req.user });
};

module.exports = {
  registerUser,
  loginUser,
  getCurrentUser
};